import { ref, onMounted, onUnmounted } from "vue";
import TencentCloudChat from "@tencentcloud/chat";
import { genTestUserSig } from "./GenerateTestUserSig";
import { defineStore } from "pinia";
import { useUserStore } from "@/store/useUserStore";

export const useTencentIM = defineStore("tencentIM", () => {
  const userStore = useUserStore();
  const SDKAppID = 1600079291; // 替换为您的 SDKAppID
  const userID = userStore.user.buyerUserId.toString();
  let _groupID = "course-group";

  const chat = TencentCloudChat.create({ SDKAppID });
  const messages = ref([]);
  const isReady = ref(false);

  const loginChat = async ({ userSig, groupID }) => {
    _groupID = `${import.meta.env.MODE === "development" ? "TEST_" : "PROD_"}${groupID}`;
    try {
      // await chat.login({ userID, userSig: userSig.userSig });
      await chat.login({ userID, userSig });
      isReady.value = chat.isReady();
      if (isReady.value) {
        await handleGroupLogic();
      } else {
        chat.on(TencentCloudChat.EVENT.SDK_READY, handleGroupLogic);
      }
    } catch (error) {
      console.warn("Login error:", error);
    }
  };

  const handleGroupLogic = async () => {
    isReady.value = true;
    try {
      // await dismissGroup();
      const response = await chat.searchGroupByID(_groupID);
      const groupExists = response.data.group;
      groupExists ? await handleGroupExists() : await createGroup();
      listen();
    } catch (error) {
      console.error("Failed to handle group logic:", error);
      await createGroup();
      listen();
    }
  };

  const handleGroupExists = async () => {
    try {
      const myGroupResponse = await chat.getGroupList();
      const myGroupList = myGroupResponse.data.group || [];
      const isMember = myGroupList.some(group => group.groupID === _groupID);

      if (!isMember) {
        await joinGroup(_groupID);
      }
      await fetchGroupMessages(_groupID);
    } catch (error) {
      console.error("Failed to check group membership:", error);
    }
  };

  const dismissGroup = async () => {
    try {
      await chat.dismissGroup(_groupID);
    } catch (error) {
      console.error("Failed to dismiss group:", error);
    }
  };

  const joinGroup = async (groupID: string) => {
    try {
      await chat.joinGroup({ groupID });
      await chat.updateMyProfile({
        nick: userStore.user.wechatName,
        avatar: userStore.user.headImage
      });
    } catch (error) {
      console.error("Failed to join group:", error);
    }
  };

  const createGroup = async () => {
    try {
      await chat.createGroup({
        name: "Live Group",
        groupID: _groupID,
        type: TencentCloudChat.TYPES.GRP_AVCHATROOM
      });
      await joinGroup(_groupID);
      await fetchGroupMessages(_groupID);
    } catch (error) {
      console.error("Failed to create group:", error);
    }
  };

  const fetchGroupMessages = async (groupID: string) => {
    try {
      const messageResponse = await chat.getMessageListHopping({
        conversationID: `GROUP${groupID}`
      });
      messages.value = messageResponse.data.messageList;
    } catch (error) {
      console.error("Failed to retrieve group chat history:", error);
    }
  };

  const sendMessageToGroup = async (message: string) => {
    try {
      const messageToSend = chat.createTextMessage({
        to: _groupID,
        conversationType: TencentCloudChat.TYPES.CONV_GROUP,
        payload: {
          text: message
        }
      });
      await chat.sendMessage(messageToSend);
      messageToSend.from = "我";
      messages.value.push(messageToSend);
      // sendMessage自己不会receive
    } catch (error) {
      console.error("Failed to send message:", error);
    }
  };

  const setupMessageListener = () => {
    chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, event => {
      const newMessages = event.data;
      const filteredMessages = newMessages.filter(
        message => message.type === "TIMTextElem"
      );
      messages.value.push(...filteredMessages);
    });
  };
  const onlineMemberCount = ref(0);

  chat.deleteConversationGroup;

  const fetchOnlineMemberCount = async () => {
    try {
      const groupProfile = await chat.getGroupProfile({ groupID: _groupID });
      onlineMemberCount.value = groupProfile.data.onlineMemberCount || 0;
    } catch (error) {
      console.error("Failed to fetch online member count:", error);
    }
  };

  chat.on(TencentCloudChat.EVENT.GROUP_LIST_UPDATED, event => {
    const updatedGroup = event.data.find(group => group.groupID === _groupID);
    if (updatedGroup) {
      onlineMemberCount.value = updatedGroup.onlineMemberCount || 0;
    }
  });

  const cleanupChat = () => {
    chat
      .logout()
      .then(() => console.log("Logged out successfully."))
      .catch(error => console.error("Failed to log out:", error));
    chat.destroy();
  };

  const listen = () => {
    setupMessageListener();
    window.addEventListener("beforeunload", cleanupChat);
  };

  const offListen = () => {
    isReady.value = false;
    cleanupChat();
    window.removeEventListener("beforeunload", cleanupChat);
  };

  return {
    messages,
    sendMessageToGroup,
    onlineMemberCount,
    loginChat,
    offListen,
    isReady
  };
});
